<?php

namespace app\forms\item;

use yii\db\Exception;
use app\forms\Model;
use app\models\Item;
use app\models\User;
use yii\web\HttpException;
use app\validators\PositiveInteger;

class UserForm extends Model
{
    public $id;
    public $name;
    public $page;
    public $pageSize;

    public function rules()
    {
        return [
            ['id', PositiveInteger::class],
            ['id', 'required'],
            ['id', 'exist', 'targetClass' => Item::class],

            ['name', 'trim'],
            ['name', 'string', 'max' => 16],

            ['page', PositiveInteger::class],
            ['page', 'default', 'value' => 1],

            ['pageSize', PositiveInteger::class],
            ['pageSize', 'default', 'value' => 10],
        ];
    }

    /**
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function getUser($param)
    {
        $form = new self;
        $form->setAttributes($param);
        if (!$form->validate()) {
            foreach ($form->getErrors() as $key => $val)
                $form->$key == 'id' ? $form->validateError() : $form->$key = '';
        }

        try {
            return (new User())->getListByItem($param);
        } catch (Exception $e) {
            $form->serverError();
        }
    }
}